import { InputProps } from "@tarojs/components/types/Input";
import { Input, View, Text } from "@tarojs/components";
import {
  ComponentType,
  ReactElement,
  useCallback,
  useMemo,
  useState,
} from "react";
import { styled } from "linaria/react";
import { useThemeState } from "../theme";

type IProps = ComponentType<
  InputProps & {
    label: string;
    width?: string;
    style?: any;
    placeholder?: string;
    onFocus?: () => void;
    onBlur?: () => void;
  }
>;

const Title: IProps = ({
  label,
  width,
  style,
  onFocus,
  onBlur,
  ...props
}): ReactElement => {
  const { theme } = useThemeState();
  const [focus, setFocus] = useState(false);
  const color = useMemo(
    () => (focus ? theme.primary : theme.color),
    [focus, theme.color, theme.primary]
  );

  const handleFocus = useCallback(() => {
    setFocus(true);
    onFocus && onFocus();
  }, [onFocus]);

  const handleBlur = useCallback(() => {
    setFocus(false);
    onBlur && onBlur();
  }, [onBlur]);

  return (
    <Container style={{ width }}>
      <Label
        style={{
          backgroundColor: theme.background,
          color,
        }}
      >
        {label}
      </Label>
      <TextInput
        type='text'
        style={{
          borderWidth: "1px",
          borderStyle: "solid",
          borderColor: color,
          ...style,
        }}
        {...props}
        onFocus={handleFocus}
        onBlur={handleBlur}
      />
    </Container>
  );
};

export default Title;

const Container = styled(View)`
  position: relative;
  padding-top: 0.5rem;
  width: 70%;
  height: 3rem;
  margin: 0.2rem 0;
`;

const TextInput = styled(Input)`
  height: 2.5rem;
  padding-left: 0.5rem;
  border-radius: 0.2rem;
`;

const Label = styled(Text)`
  position: absolute;
  top: 0;
  left: 0.5rem;
  font-size: 0.5rem;
  padding: 0 0.2rem;
`;
